/**
 * 
 */
package droid.insane.logic;

import java.io.IOException;

import android.util.Log;
import au.com.bytecode.opencsv.CSVParser;
import droid.insane.database.DBHandler;

/**
 * @author Sandamal
 * Parses a csv file
 */
public class StringHandler {

	private static StringHandler stringHandlerInstance;
	private DBHandler dbHandler;

	private StringHandler() {
	}

	public static StringHandler getStringHandler() {
		if (stringHandlerInstance == null) {
			stringHandlerInstance = new StringHandler();
		}
		return stringHandlerInstance;
	}

	/**
	 * Parses the csv string
	 * 
	 * @param dataString
	 *            a String containing market data of all the listed companies
	 */
	public void getData(String dataString) {
		dbHandler = DBHandler.getDBHandler(null);
		try {
			dbHandler.openToWrite();
		} catch (Exception e) {
			Log.d(ConstantValues.TAG, e.getMessage());
		}
		dbHandler.deleteMarketData();

		CSVParser csvParser = new CSVParser();
		String[] dataOfCompanies = dataString.split("\n");

		Log.d(ConstantValues.TAG, "String Handler - Number of companies "
				+ dataOfCompanies.length);

		for (String s : dataOfCompanies) {
			try {
				dbHandler.marketDataEntry(csvParser.parseLineMulti(s));
			} catch (IOException e) {
				Log.e(ConstantValues.TAG, e.getMessage());
			}
		}
		dbHandler.close();
	}
}
